package org.swift.mashup.engine.concurrency.memory;

import java.util.Collection;
import java.util.Collections;

import org.swift.commons.xml.XmlUtils;
import org.w3c.dom.Node;

public class BytesMemoryItem extends MemoryItem {

	private final byte[] bytes;


	public BytesMemoryItem(int id, byte[] bytes, MemoryType type) {
		super(id, type);
		this.bytes = bytes;
	}

	public BytesMemoryItem(int id, String bytes, MemoryType type) {
		super(id, type);
		this.bytes = bytes.getBytes();
	}

	@Override
	public Object getValue() {
		return bytes;
	}

	@Override
	public Collection<byte[]> toCollection() {
		return Collections.singletonList(bytes);
	}
	
	@Override
	public Node toNode() {
		String xml = toXML();		
		try {
			return XmlUtils.toDocument(xml);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String toString() {
		return new String(bytes);
	}

	@Override
	public String toXML() {
		if (XmlUtils.isXml(toString())) {
			return toString();
		} else {
			return "<" + this.getType().getName() + ">" 
				+ toString() 
				+ "</" + this.getType().getName() + ">";
		}
		
	}

}
